/*
 * @lc app=leetcode.cn id=135 lang=javascript
 *
 * [135] 分发糖果
 */

// @lc code=start
/**
 * @param {number[]} ratings
 * @return {number}
 */
var candy = function (ratings) {
  let n = ratings.length;
  if (n === 1) return 1;
  if (n === 2) return ratings[0] === ratings[1] ? 2 : 3;
  const candy = new Array(n).fill(1);
  // 左向右
  for (let i = 1; i < n; i++) {
    if (ratings[i] > ratings[i - 1]) {
      candy[i] = candy[i - 1] + 1;
    }
  }
  // 右向左，需要判断是否已经满足条件
  for (let i = n - 1; i > 0; i--) {
    if (ratings[i] < ratings[i - 1] && candy[i] >= candy[i - 1]) {
      candy[i - 1] = candy[i] + 1;
    }
  }
  return candy.reduce((acc, cur) => acc + cur, 0);
};
// @lc code=end
